<template>
  <!-- <view>

		<div id="container"></div>
	<button >获取位置</button>
	</view> -->
  <div class="mapPosition">
    <div class="map-title">
      <p class="title">运动位置定位</p>
      <p>此次运动你将运动{{ meter }}米</p>
      <button @click="add(meter)" >提交</button>
      <div class="positionInfo">
        <span>位置信息:</span
        ><span>{{
          positionInfo.formattedAddress
            ? positionInfo.formattedAddress
            : '出了点小bug'
        }}</span>
      </div>
    </div>
    <div id="iCenter"></div>

    <div id="pickerBox">
      <input v-model="pickerInput" id="P" placeholder="输入关键字选取地点" />
      <div id="poiInfo"></div>
    </div>
    <h4>左击获取经纬度：</h4>

    <input type="text" readonly="true" />
    {{ value }}
    <div id="panel"></div>
  </div>
</template>


<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import { shallowRef } from '@vue/reactivity'
import axios from 'axios'

window._AMapSecurityConfig = {
  securityJsCode: 'c7326d012d3d290639c3636d091eb7cc',
}
export default {
  //   name: 'mapPosition',
  data() {
    return {
      positionInfo: {},
      value: {},
      distance: {},
      sgetlng: 118.055469,
      sgetLat: 36.816425,
      egetlng: 116.39903,
      egetLat: 39.84505,
      pickerInput: '',
      meter: {},
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    initMap() {
      AMapLoader.load({
        key: 'b4dbbf80edba6962070d9ea39c610da1', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '1.4.5', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          'AMap.Geolocation',
          'AMap.walking',
          'AMap.Autocomplete',
          'AMap.PlaceSearch',
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        zoom: 50,
        AMapUI: {
          version: '1.1',
          plugins: ['overlay/SimpleMarker'],
        },
        callback: 'onLoad',
      })
        .then(AMap => {
          var that = this
          var mapObj = new AMap.Map('iCenter', {
            //设置地图容器id
            viewMode: '3D', //是否为3D地图模式
            //   zoom:30,           //初始化地图级别
            //         //初始化地图中心点位置
            resizeEnable: true,
          })

          mapObj.on('click', function (e) {
            that.value = e.lnglat.getLng() + ',' + e.lnglat.getLat()
            that.egetlng = e.lnglat.getLng()
            that.egetLat = e.lnglat.getLat()
            console.log(that.value)

            AMap.plugin(['AMap.Walking'], function () {
              var walkOption = {
                map: mapObj,
                panel: 'panel',
                hideMarkers: false,
                isOutline: true,
                outlineColor: '#ffeeee',
                autoFitView: true,
              }
              var walking = new AMap.Walking(walkOption)
              walking.clear()
              // 步行导航

              //根据起终点坐标规划步行路线
              walking.search(
                [that.sgetlng, that.sgetLat],
                [that.egetlng, that.egetLat],
                function (status, result) {
                  if (status === 'complete') {
                    console.log('步行路线数据查询成功')
                    console.log(result.routes[0].distance)
                    that.meter = result.routes[0].distance
                  } else {
                    window.alert('距离太远了！！！   请重新选定目的地')
                    console.log('步行路线数据查询失败' + result)
                  }
                }
              )
            })
          })

          AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {
            console.log(that.pickerInput)
            var temp = document.getElementById('PickerInput')
            console.log(temp)
            var poiPicker = new PoiPicker({
              //city:'北京',
              input: 'P',
            })
            //初始化poiPicker
            poiPickerReady(poiPicker)
          })

          function poiPickerReady(poiPicker) {
            window.poiPicker = poiPicker

            var marker = new AMap.Marker()

            var infoWindow = new AMap.InfoWindow({
              offset: new AMap.Pixel(0, -20),
            })

            //选取了某个POI
            poiPicker.on('poiPicked', function (poiResult) {
              var source = poiResult.source,
                poi = poiResult.item,
                info = {
                  source: source,
                  id: poi.id,
                  name: poi.name,
                  location: poi.location.toString(),
                  address: poi.address,
                }

              marker.setMap(mapObj)
              infoWindow.setMap(mapObj)

              marker.setPosition(poi.location)
              infoWindow.setPosition(poi.location)

              infoWindow.setContent(
                'POI信息: <pre>' + JSON.stringify(info, null, 2) + '</pre>'
              )
              infoWindow.open(mapObj, marker.getPosition())

              mapObj.setCenter(marker.getPosition())
            })

            poiPicker.onCityReady(function () {
              poiPicker.suggest('美食')
            })
          }
          AMap.plugin(['AMap.ControlBar'], function () {
            // 添加 3D 罗盘控制
            mapObj.addControl(new AMap.ControlBar())
          })
          //这里是要获取地图容器的id,所以要写在mounted之中
          var geolocation
          var that = this
          AMap.plugin('AMap.Geolocation', function () {
            geolocation = new AMap.Geolocation({
              enableHighAccuracy: true, // 是否使用高精度定位，默认:true
              timeout: 100000, // 超过10秒后停止定位，默认：无穷大
              maximumAge: 0, // 定位结果缓存0毫秒，默认：0
              convert: false, // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
              showButton: true, // 显示定位按钮，默认：true
              buttonPosition: 'LB', // 定位按钮停靠位置，默认：'LB'，左下角
              buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
              showMarker: true, // 定位成功后在定位到的位置显示点标记，默认：true
              showCircle: false, // 定位成功后用圆圈表示定位精度范围，默认：true
              panToLocation: true, // 定位成功后将定位到的位置作为地图中心点，默认：true
              zoomToAccuracy: true, // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            })
            mapObj.addControl(geolocation)
            geolocation.getCurrentPosition()
            // console.log(that.positionInfo)
            // that.onComplete(geolocation);
            AMap.event.addListener(geolocation, 'complete', that.onComplete) // 返回定位信息
            AMap.event.addListener(geolocation, 'error', that.onError) // 返回定位出错信息
          })
          //     this.map = new AMap.Map("container",{  //设置地图容器id
          //         viewMode:"3D",    //是否为3D地图模式
          //         zoom:50,           //初始化地图级别
          //         //初始化地图中心点位置
          //     });
          // 	 const self = this
          // AMap.plugin('AMap.Geolocation', function () {
          //     var geolocation = new AMap.Geolocation({
          //         // 是否使用高精度定位，默认：true
          //         enableHighAccuracy: true,
          //         // 设置定位超时时间，默认：无穷大
          //         timeout: 10000,
          //     })

          //     geolocation.getCurrentPosition()
          //     AMap.event.addListener(geolocation, 'complete', onComplete);
          //     AMap.event.addListener(geolocation, 'error', onError);

          //     function onComplete(data) {
          //         // data是具体的定位信息
          //         console.log('定位成功信息：', data);
          //     }

          //     function onError(data) {
          //         // 定位出错
          //         console.log('定位失败错误：', data);
          //         // 调用ip定位
          //         self.getLngLatLocation();
          //     }
          // })
        })
        .catch(e => {
          console.log(e)
        })
    },

    add(meter) {
      // console.log("========")
      // console.log(id)
      // console.log("========")
      axios.post('https://qcqvax.api.cloudendpoint.cn/sport',{style: "步行",
        distance: meter}).then(function(response){
          console.log("这是响应"+response)
        if (response) {
          window.alert("添加成功", "提示", {
            type: 'success'
          });
        }
      }, {
        style: "步行",
        distance: meter
      });
    },
    onComplete(obj) {
      this.positionInfo = obj
      var res =
        '经纬度：' +
        obj.position +
        '\n精度范围：' +
        obj.accuracy +
        '米\n定位结果的来源：' +
        obj.location_type +
        '\n状态信息：' +
        obj.info +
        '\n地址：' +
        obj.formattedAddress +
        '\n地址信息：' +
        obj.addressComponent
      //   JSON.stringify(obj.addressComponent, null, 4)
      console.log(this.positionInfo.message)
      console.log(obj.position)
      console.log(res)
    },
    onError(obj) {
      alert(obj.info + '--' + obj.message)
      console.log(obj)
    },
  },
}
</script>

<style lang="scss">
body {
  text-align: center;
}
#container {
  margin: 0px auto;
  width: 1000px;
  height: 500px;
  align-content: center;
}
.mapPosition {
  width: 100%;
  height: 100%;
  .map-title {
    .title {
      height: 60px;
      line-height: 60px;
      font-size: 28px;
    }
    .positionInfo {
      height: 50px;
      span {
        display: inline-block;
        height: 30px;
        line-height: 30px;
        font-size: 21px;
      }
    }
  }
  #iCenter {
    width: 80%;
    height: 600px;
    margin: 0 auto;
    float: left;
  }
}
#panel {
  position: fixed;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 10px;
  right: 10px;
  width: 280px;
}
#panel .amap-call {
  background-color: #009cf9;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
}
#panel .amap-lib-walking {
  border-bottom-left-radius: 4px;
  border-bottom-right-radius: 4px;
  // overflow: hidden;
}
#pickerBox {
  position: absolute;
  z-index: 9999;
  top: 50px;
  right: 30px;
  width: 300px;
}

#P {
  width: 200px;
  height: 50px;
  padding: 5px 5px;
}

#poiInfo {
  background: #fff;
}

.amap_lib_placeSearch .poibox.highlight {
  background-color: #cae1ff;
}

.amap_lib_placeSearch .poi-more {
  display: none !important;
}
</style>
